package com.jjh.index;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import com.jjh.util.HtmlDocParser;

public class IndexManager {
	
	private String dataDir = "G:\\lucene\\source";
	private String indexDir = "G:\\lucene\\index";
	
	public IndexManager(){
		String path = getClass().getResource("").getPath().replaceAll("%20", " ");
		this.dataDir = path.substring(0, path.indexOf("/WEB-INF")) + File.separator + "source";
		this.indexDir = path.substring(0, path.indexOf("/WEB-INF")) + File.separator + "index";
	}

	//判断索引是否已经创建
	public boolean ifIndexExist() {
		File directory = new File(indexDir);
		//在索引文件夹中存在文件就认为建立好索引了
		if(directory.listFiles().length > 0){
			return true;
		}
		return false;
	}

	//创建索引
	public boolean createIndex() throws IOException {
		if(ifIndexExist() == true){
			return true;
		}
		
		//读取数据源
		File dir = new File(dataDir);
		if(!dir.exists()){
			return false;
		}
		
		File[] htmls = dir.listFiles();
		Directory fsDirectory = FSDirectory.open(new File(indexDir));
		Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_21);
		IndexWriter indexWriter = new IndexWriter(fsDirectory,
				analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED);
		for(int i = 0;i < htmls.length; i ++){
			String htmlPath = htmls[i].getAbsolutePath();
			if(htmlPath.endsWith(".html") || htmlPath.endsWith(".htm")){
				addDocument(htmlPath, indexWriter);
			}
		}
		
		System.out.println(indexWriter.numDocs());
		indexWriter.optimize();
		indexWriter.close();
		
		return true;
	}

	//写入到索引文件中
	private void addDocument(String htmlPath, IndexWriter indexWriter) {
		HtmlDocParser htmlParser = new HtmlDocParser(htmlPath);
		String path = htmlParser.getPath();
		String title = htmlParser.getTitle();
		String content = htmlParser.getContent();
		
		Document doc = new Document();
		doc.add(new Field("path", path, Field.Store.YES, Field.Index.NO));
		doc.add(new Field("title", title, Field.Store.YES, Field.Index.ANALYZED));
		try {
			doc.add(new Field("content", new FileReader(new File(htmlPath))));
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		try{
			indexWriter.addDocument(doc);
		} catch (Exception e){
			e.printStackTrace();
		}
	}

	//得到索引文件的存放位置
	public Directory getIndexDir() throws IOException {
		Directory d = FSDirectory.open(new File(indexDir));
		return d;
	}

}
